﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace CSharpHelpers.Contorls
{
    class DataGridViewHelper
    {
        //獲得選中行
        public static int GetSelectedId(DataGridView dgvList, int rowIndex, string colName)
        {
            if (rowIndex != -1)
            {
                if (dgvList.Rows[rowIndex].Cells[colName].FormattedValue != null)
                {
                    return Convert.ToInt32(dgvList.Rows[rowIndex].Cells[colName].FormattedValue);
                }
            }

            return 0;
        }

        //dategridview樣式
        public static void SetDateGridViewDefaultStyle(DataGridView dgv)
        {
            dgv.RowHeadersVisible = false;
            dgv.AutoGenerateColumns = false;
            //隔行換色
            dgv.RowsDefaultCellStyle.BackColor = Color.FromArgb(222, 244, 244);// Color.FromArgb(4, 230, 228);
            dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.White;// Color.FromArgb(187, 227, 227);             
            dgv.ReadOnly = true;
            dgv.EnableHeadersVisualStyles = false;
            dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dgv.ColumnHeadersHeight = 38;
            dgv.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(183, 235, 235);
            dgv.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 12f);
            dgv.RowsDefaultCellStyle.Font = new Font("宋体", 10f);
            dgv.RowTemplate.Height = 30;
            dgv.BackgroundColor = Color.White;
            dgv.BorderStyle = BorderStyle.None;
            dgv.GridColor = Color.FromArgb(145, 192, 192);

            dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        public static DataGridViewCheckBoxColumn BuildCheckBoxColumn(string header, string name, string datafield, bool bVisible)
        {
            DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
            column.HeaderText = header;
            column.Name = name;
            column.DataPropertyName = datafield;
            column.Visible = bVisible;

            column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            return column;
        }

        public static DataGridViewTextBoxColumn BuildColumn(string header, string name, string datafield, bool bVisible)
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
            column.HeaderText = header;
            column.Name = name;
            column.DataPropertyName = datafield;
            column.Visible = bVisible;
            column.ReadOnly = true;
            column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            return column;
        }


        public static DataGridViewImageColumn BuildImagesColumn(string header, string name, string datafield, bool bVisible, string imageUrl)
        {
            DataGridViewImageColumn column = new DataGridViewImageColumn();
            if (!string.IsNullOrEmpty(imageUrl))
                column.Image = Image.FromFile(imageUrl);
            column.HeaderText = header;
            column.Name = name;
            if (!string.IsNullOrEmpty(datafield))
            {
                column.DataPropertyName = datafield;
            }
            column.Visible = bVisible;
            return column;
        }

        /// <summary>
        /// dataGrivView排序方法 注意列名一定要和实体名一样 才可以排序
        /// </summary>
        /// <typeparam name="T">List的類型</typeparam>
        /// <param name="name">列名</param>
        /// <param name="dicSort">排序規則</param>
        /// <param name="dgv">控件</param>
        /// <param name="list">List</param>
        public static void SetDateGridViewSort<T>(string name, Dictionary<string, bool> dicSort, DataGridView dgv, List<T> list)
        {

            //获取实体里面有没有这个属性
            Type type = list.GetType();
            if (type.IsGenericType)
            {
                Type[] genericArgTypes = type.GetGenericArguments();
                PropertyInfo propertyInfo = genericArgTypes[0].GetProperty(name);
                if (propertyInfo == null) return;
            }

            bool isAsc = true;

            //判断排序方式
            if (dicSort.ContainsKey(name))
            {
                isAsc = dicSort[name];
                dicSort[name] = !isAsc;
            }
            else
            {
                dicSort.Add(name, !isAsc);
            }

            //根据名称排序
            if (isAsc)
            {
                list = list.OrderBy(p => p.GetType().GetProperty(name).GetValue(p, null)).ToList();
            }
            else
            {
                list = list.OrderByDescending(p => p.GetType().GetProperty(name).GetValue(p, null)).ToList();
            }
            dgv.DataSource = list;
        }

        public static void SetCheckboxInDataGridView(DataGridView dgv, CheckBox chk, int width)
        {
            int x = dgv.Location.X + width / 2 - chk.Width / 2 + 1;
            int y = dgv.Location.Y + dgv.ColumnHeadersHeight / 2 - chk.Height / 2 + 1;
            chk.Location = new Point(x, y);
        }

        /// <summary>
        /// 获取datagridview选中list
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="dic"></param>
        public static Dictionary<int, bool> GetCheckListByGridView(DataGridView dgv, Dictionary<int, bool> dic)
        {
            int id = 0;
            bool isCheck = false;

            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (!row.IsNewRow)
                {
                    id = GetRightIntStr(row.Cells["id"].Value.ToString());
                    isCheck = Convert.ToBoolean(row.Cells["CheckBox"].Value);

                    if (dic.ContainsKey(id))
                    {
                        dic[id] = isCheck;
                    }
                    else
                    {
                        dic.Add(id, isCheck);
                    }
                }
            }

            return dic;
        }

        /// <summary>
        /// 设置datagridview的复选框
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="dic"></param>
        public static void SetCheckListByGridView(DataGridView dgv, Dictionary<int, bool> dic)
        {
            int id = 0;

            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (!row.IsNewRow)
                {
                    id = GetRightIntStr(row.Cells["id"].Value.ToString());

                    if (dic.ContainsKey(id))
                    {
                        row.Cells["CheckBox"].Value = dic[id];
                    }
                }
            }
        }

        public static int GetRightIntStr(string value)
        {
            int result = 0;
            int.TryParse(value, out result);
            return result;
        }
    }
}
